<?php
class testModel extends RPHP_Model
{
    //首页
    public function indexList()
    {

        //广告
        $sql      = "SELECT * FROM {$this->_prefix['primary']}adv WHERE `status`=1 AND `position` IN (1,2,7,8,9) ORDER BY `sorts` asc,`ctime` desc";
        $advList  = $this->sql($sql);
        $advlist1 = array();
        $advlist2 = array();
        $advlist3 = array();
        $advlist4 = array();
        $advlist5 = array();
        $url      = "";

        foreach ($advList as $v) {

            if ($v['pic']) {
                $pics     = $this->getPic($v['pic']);
                $v['pic'] = $pics[0]['img_url'];
            }

            $url = trim($v['url']);
            if (empty($url)) {

                if($v['position']!=2){
                    $goods_ids = explode(',', $v['goods_id']);
                    if (count($goods_ids) > 1) {
                        $v['url'] = "/index/goodslist?goods_ids=" . $v['goods_id'];
                    } elseif ($v['goods_id'] != "") {
                        $adv_goods_ids[] = $v['goods_id'];
                        $v['url']        = "/index/goodsdetail?goods_id=" . $v['goods_id'];
                    }

                }else{

                    $v['url']        = "/rcm/index?caid=" . $v['caid'];

                }



            }



            if ($v['position'] == 1) {
                $advlist1[] = $v;

            }

            if ($v['position'] == 7) {
                $advlist2 = $v;

            }

            if ($v['position'] == 8) {
                $advlist3[] = $v;

            }

            if ($v['position'] == 9) {
                $advlist4[] = $v;

            }

            if ($v['position'] == 2) {
                $advlist5[] = $v;

            }


        }

        //今日特卖
      /*  $sql       = "SELECT `thumb_docid`,`show_docid`,`goods_id`,`goods_name`,`sales_count`,`shop_price`,`goods_number`,`market_price`,`ximi_price`,`price_me`,`coupon_price` FROM {$this->_prefix['primary']}goods_data WHERE `is_delete`=0 AND `is_on_sale`=1 AND `shopid`=1 AND `weight`>0 ORDER BY `weight` DESC, `sales_count` desc,goods_id desc limit 50";
        $goodsList = $this->sql($sql);*/
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $spes = $this->table("today_special")->findAllBySql("`start_time` >".$beginToday." AND `start_time`<".$endToday." ORDER BY `start_time` ASC");

        if($spes){
            foreach($spes as $k=>$v){
                $special[$k]['id'] = $v['id'];
                $special[$k]['time'] = date("H:i",$v['start_time']);
                if($v['start_time'] >time()){
                    $special[$k]['status_name'] = "即将开始";
                    $special[$k]['status'] = 1;
                }elseif($v['end_time'] <time()){
                    $special[$k]['status_name'] = "已结束";
                    $special[$k]['status'] = 3;
                }else{
                    $special[$k]['status'] =2;
                    $special[$k]['status_name'] = "抢购中";
                }

            }

        }

        //分类信息
        $cate = $this->table('goods_category')->findAllBySql("`fucaid`=0 AND `stat`=1");

        if($cate){
            foreach($cate as $key=>$v){
                $goods[$key]['img'] = "/style/images/index/s_11.png";
                if ($v['docid']) {
                    $p                              = $this->getPic($v['docid']);
                    $cate[$key]['img'] = $p[0]['img_url'];
                }

            }

        }
       /* foreach ($goodsList as $key => &$val) {
            if ($val['thumb_docid']) {
                $p                              = $this->getPic($val['thumb_docid']);
                $goodsList[$key]['thumb_docid'] = $p[0]['img_url'];
            } else {
                $val['thumb_docid'] = "/style/wei/images/home/xihuan-pic1.png";

            }
            $sql                 = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` =" . $val['goods_id'];
            $goodsnumber         = $this->db->getone($sql);
            $val['goods_number'] = $goodsnumber;
        }*/

/*        if ($adv_goods_ids) {
            $sql = "SELECT `goods_id`,`shop_price`,`ximi_price`,`price_me`,`coupon_price` FROM {$this->_prefix['primary']}goods_data WHERE `is_delete`=0 AND `is_on_sale`=1 AND `goods_id` IN (" . implode(",", array_unique($adv_goods_ids)) . ")";
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $goods[$r['goods_id']] = $r;
                }
            }
        }*/

        $arr['advList1']  = $advlist1;
        $arr['advList2']  = $advlist2;
        $arr['advList3']  = $advlist3;
        $arr['advList4']  = $advlist4;
        $arr['advList5'] = $advlist5;
        $arr['special'] = $special;
        $arr['cate'] = $cate;
   //dd($arr);


        return $arr;
    }
    //今日特卖异步数据
    public function ajaxGetSpecial()
    {
        $id = intval($_POST['id']);
        $data = $this->table("today_special")->findBySql("`id`=".$id);
        $goods = [];
        if($data['goods_ids']){

            $goods = $this->table("goods_data")->findAllBySql("`goods_id` IN (".$data['goods_ids'].") AND `is_on_sale`=1 AND `is_delete`=0"," `thumb_docid`,`show_docid`,`hot_docid`,`goods_id`,`goods_name`,`goods_title`,`sales_count`,`shop_price`,`goods_number`,`market_price`,`ximi_price`,`price_me`,`coupon_price`");
            if($goods){
                foreach($goods as $key=>$val){

                    $sql                 = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` =" . $val['goods_id'];
                    $goodsnumber         = $this->db->getone($sql);
                    $goods[$key]['stock_number'] = $goodsnumber;

                    if ($val['hot_docid']) {
                        $p                              = $this->getPic($val['hot_docid']);
                        $goods[$key]['img'] = $p[0]['img_url'];
                    } else {

                        $goods[$key]['img'] = "/style/wei/images/home/channel-pic.jpg";
                    }
                }
            }
        }
        return $goods;

    }

    //获取单个商品
    public function getSingleGoods($goods_id)
    {

        $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_data WHERE `goods_id`=" . intval($goods_id) . " AND `is_delete`=0";
        $data = $this->db->getrow($sql);

        if ($data) {

            if ($data['is_on_sale'] == 1) {
                if ($this->_user['uid']) {

                    $this->saveGoodsLog($data['goods_id']);

                    //添加我的足迹
                    $sql     = "SELECT `id` FROM {$this->_prefix['primary']}goods_history WHERE `uid`=" . $this->_user['uid'] . " AND `goods_id`=" . $data['goods_id'];
                    $foot_id = $this->db->getone($sql);
                    // 更新足迹
                    if ($foot_id > 0) {
                        $sql = "UPDATE {$this->_prefix['primary']}goods_history SET `create_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `id`=" . $foot_id;
                        $this->sql($sql);
                    }
                    // 插入足迹
                    else {
                        $sql = "INSERT INTO {$this->_prefix['primary']}goods_history (`uid`,`goods_id`,`create_time`) VALUES (" . $this->_user['uid'] . "," . $data['goods_id'] . "," . time() . ")";
                        $this->sql($sql);
                    }

                    // 检查是否已经收藏
                    $sql                = "SELECT `id` FROM {$this->_prefix['primary']}goods_collection WHERE `uid`=" . $this->_user['uid'] . " AND `goods_id`=" . $data['goods_id'] . " AND `state`=1";
                    $data['collection'] = $this->db->getone($sql);

                    //供应商信息
                    $sql                = "SELECT `headimgurl`,`supplier`,`id` FROM {$this->_prefix['primary']}supplier WHERE `id`=" .$data['supplierid'];
                    $data['supplier'] = $this->db->getrow($sql);
                }

                // 计算折扣
                if ($data['market_price'] > $data['shop_price']) {
                    $data['discount_percent'] = number_format($data['shop_price'] / $data['market_price'], 2, ".", "");
                }

                if ($data['discount_percent'] == 1) {

                    $data['discount_percent'] = 0;
                } else {
                    $data['discount_percent'] = $data['discount_percent'] * 10;
                }

                if ($data['market_price'] <= $data['shop_price']) {

                    $data['discount_percent'] = 0;
                }

                //获取库存
                $sql                  = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $goods_id . " LIMIT 1";
                $data['stock_number'] = $this->db->getone($sql);

                //获取封面
                if ($data['pic_docid'] > 0) {
                    $docid[] = $data['pic_docid'];
                }

                if ($data['pic2_docid'] > 0) {
                    $docid[] = $data['pic2_docid'];
                }

                if ($data['pic3_docid'] > 0) {
                    $docid[] = $data['pic3_docid'];
                }

                if ($data['pic4_docid'] > 0) {
                    $docid[] = $data['pic4_docid'];
                }

                if ($data['pic5_docid'] > 0) {
                    $docid[] = $data['pic5_docid'];
                }

                $data['docids'] = $docid;

                if ($docid) {
                    $data['docs'] = $this->getDocs($docid);
                }
            }

            return $data;
        }
    }

    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    //添加商品浏览记录
    public function addGoodsClickCount($goods_id)
    {
        if ($goods_id) {
            $sql = "UPDATE {$this->_prefix['primary']}goods_data set click_count=click_count+1 where goods_id=" . $goods_id . " and shopid=1";
            return $this->sql($sql);
        }
    }

    // 获取商品数据
    public function getGoodsList_1($para, $page, $pagesize = 100)
    {

        // 是否继续执行查询
        $donext = true;

        $where = "`is_on_sale`= 1 AND `is_delete`= 0";

        switch ($para['order']) {
            case 1:
                $orderby = "`warehouse_type` ASC,`weight` DESC,`shop_price` DESC";
                break;
            case 2:
                if ($para['price']) {
                    $orderby = "`shop_price` DESC,`warehouse_type` ASC,`weight` DESC";
                } else {

                    $orderby = "`shop_price` ASC,`warehouse_type` ASC,`weight` DESC";
                }
                break;
            case 3:
                $orderby = "`discount_percent` ASC,`warehouse_type` ASC,`weight` DESC,`shop_price` DESC";
                break;
            case 4:
                $orderby = "`sales_count` DESC,`warehouse_type` ASC,`weight` DESC,`shop_price` DESC";
                break;
            default:
                $orderby = "`warehouse_type` ASC,`weight` DESC,`shop_price` DESC";
        }

        if ($para['keywords'] != "") {

            $words = $this->getScwsWord($para['keywords']);
            if (count($words) > 0) {
                $scws_data = $this->getScwsData($words);

                if (is_array($scws_data['goods_ids']) && count($scws_data['goods_ids']) > 0) {
                    $where .= " AND `goods_id` IN (" . implode(",", $scws_data['goods_ids']) . ")";
                    $scws_sql = $scws_data['sql'];
                }
                // 没有符合要求的分词结果则中止查询
                else {
                    $donext = false;
                }
            }

        } else {
            if ($para['caid']) {
                $where .= " AND `caid` = " . $para['caid'];
                //所属分类广告
                $sql         = "SELECT * FROM {$this->_prefix['primary']}adv WHERE `caid`=" . $para['caid'] . " AND `status`=1  ORDER BY `sorts` asc,`ctime` desc";
                $cateAdvlist = $this->sql($sql);
                foreach ($cateAdvlist as $k => $v) {
                    if ($v['pic']) {
                        $pics                   = $this->getPic($v['pic']);
                        $cateAdvlist[$k]['pic'] = $pics[0]['img_url'];
                    }
                    $goods_idss = explode(',', $v['goods_id']);
                    if (count($goods_idss) > 1) {
                        $cateAdvlist[$k]['url'] = "/index/goodslist?goods_ids=" . $v['goods_id'] . "&caid=" . $para['caid'];
                    } else {

                        $cateAdvlist[$k]['url'] = "/index/goodsdetail?goods_id=" . $v['goods_id'] . "&caid=" . $para['caid'];
                    }

                }

            }
            if ($para['brand_id']) {
                $where .= " AND `brand_id` = " . $para['brand_id'];

            }
            if ($para['goods_ids']) {
                $where .= " AND `goods_id` IN (" . $para['goods_ids'] . ")";
            }

        }

        if ($donext) {
            //echo $where;die;
            $sql = "SELECT COUNT(`goods_id`) AS `cnt` FROM {$this->_prefix['primary']}goods_data WHERE " . $where;

            $cnt = $this->db->getone($sql);
            // echo $cnt;die;
            if ($cnt > 0) {

                if ($para['type'] == "return" && $page > 1) {
                    $p     = $page * $pagesize;
                    $limit = " LIMIT 0," . $p;

                } else {
                    $start = ($page - 1) * $pagesize;

                    $limit = " LIMIT " . $start . "," . $pagesize;

                }

                $sql = "SELECT * FROM {$this->_prefix['primary']}goods_data WHERE " . $where . " ORDER BY " . $orderby . $limit;

                $rs = $this->sql($sql);

                if ($rs) {
                    foreach ($rs as $r) {

                        if ($r['thumb_docid'] > 0) {
                            $docids[] = $r['thumb_docid'];
                        } elseif ($r['pic_docid'] > 0) {
                            $docids[] = $r['pic_docid'];
                        }

                        $goods_ids[] = $r['goods_id'];

                    }

                    // 获取库存
                    $sql = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` IN (" . implode(",", $goods_ids) . ")";
                    $tmp = $this->sql($sql);

                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $goods_number[$r['goods_id']] = $r['number'];
                        }

                    }

                    if ($docids) {
                        $docs = $this->getDocs($docids);
                    }

                    foreach ($rs as $k => $r) {

                        if ($r['thumb_docid'] > 0 && $docs[$r['thumb_docid']]) {

                            $rs[$k]['thumb_docid'] = $docs[$r['thumb_docid']];

                        } elseif ($r['pic_docid'] > 0 && $docs[$r['pic_docid']]) {

                            $rs[$k]['thumb_docid'] = $docs[$r['pic_docid']];

                        }

                        if ($goods_number[$r['goods_id']] > 0) {
                            $rs[$k]['goods_number'] = $goods_number[$r['goods_id']];
                        } else {
                            $rs[$k]['goods_number'] = 0;
                        }

                    }

                }

            }

            // 获取分类
            if ($para['caid'] > 0) {
                $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE `caid`=" . $para['caid'];
                $caid = $this->db->getrow($sql);
            }

            // 获取品牌
            if ($para['brand_id'] > 0) {
                $sql   = "SELECT * FROM {$this->_prefix['primary']}brand WHERE `brand_id`=" . $para['brand_id'];
                $brand = $this->db->getrow($sql);
                if ($brand['brand_pic'] > 0) {
                    $tmp = $this->getDocs($brand['brand_pic']);

                    if ($tmp[$brand['brand_pic']]) {
                        $brand['logo'] = $tmp[$brand['brand_pic']];
                    }
                }
            }
        }

        return array(
            'page'        => $page,
            'maxpage'     => ceil($cnt / $pagesize),
            'count'       => $cnt,
            'data'        => $rs,
            'para'        => $para,
            'docs'        => $docs,
            'brand'       => $brand,
            'cateAdvlist' => $cateAdvlist,
            'caid'        => $caid['name'],
        );

    }
    // 获取商品数据
    public function getGoodsList($para, $page, $pagesize = 100)
    {

        // 是否继续执行查询
        $donext = true;

        $where = "`is_on_sale`= 1 AND `is_delete`= 0";

        $sort_val = $para['sort_val'] > 1 ? "DESC" : "ASC";

        switch ($para['sort_type']) {
            case 1:
                $orderby = "`weight` DESC,`shop_price` DESC";
                break;
            case 2:
                $orderby = "`discount_percent` " . $sort_val . ",`weight` DESC,`shop_price` DESC";
                break;
            case 3:
                $orderby = "`shop_price` " . $sort_val . ",`weight` DESC";
                break;
            case 4:
                $orderby = "`sales_count` " . $sort_val . ",`weight` DESC,`shop_price` DESC";
                break;
            default:
                $orderby = "`weight` DESC,`shop_price` DESC";
        }

        if ($para['keywords'] != "") {

            /*$words = $this->getScwsWord($para['keywords']);
            if (count($words) > 0) {
            $scws_data = $this->getScwsData($words);

            if (is_array($scws_data['goods_ids']) && count($scws_data['goods_ids']) > 0) {
            $where .= " AND `goods_id` IN (" . implode(",", $scws_data['goods_ids']) . ")";
            $scws_sql = $scws_data['sql'];
            }
            // 没有符合要求的分词结果则中止查询
            else {
            $donext = false;
            }
            }*/

            $where .= " AND `goods_name` LIKE '%" . $para['keywords'] . "%'";

        } else {
            if ($para['caid']) {
                $where .= " AND `caid` = " . $para['caid'];
                //所属分类广告
                $sql         = "SELECT * FROM {$this->_prefix['primary']}adv WHERE `caid`=" . $para['caid'] . " AND `status`=1  ORDER BY `sorts` asc,`ctime` desc";
                $cateAdvlist = $this->sql($sql);
                foreach ($cateAdvlist as $k => $v) {
                    if ($v['pic']) {
                        $pics                   = $this->getPic($v['pic']);
                        $cateAdvlist[$k]['pic'] = $pics[0]['img_url'];
                    }
                    $goods_idss = explode(',', $v['goods_id']);
                    if (count($goods_idss) > 1) {
                        $cateAdvlist[$k]['url'] = "/index/goodslist?goods_ids=" . $v['goods_id'] . "&caid=" . $para['caid'];
                    } else {

                        $cateAdvlist[$k]['url'] = "/index/goodsdetail?goods_id=" . $v['goods_id'] . "&caid=" . $para['caid'];
                    }

                }

            }
            if ($para['brand_id']) {
                $where .= " AND `brand_id` = " . $para['brand_id'];

            }
            if ($para['goods_ids']) {
                $where .= " AND `goods_id` IN (" . $para['goods_ids'] . ")";
            }

        }

        if ($donext) {
            //echo $where;die;
            $sql = "SELECT COUNT(`goods_id`) AS `cnt` FROM {$this->_prefix['primary']}goods_data WHERE " . $where;

            $cnt = $this->db->getone($sql);
            // echo $cnt;die;
            if ($cnt > 0) {

                if ($para['type'] == "return" && $page > 1) {
                    $p     = $page * $pagesize;
                    $limit = " LIMIT 0," . $p;

                } else {
                    $start = ($page - 1) * $pagesize;

                    $limit = " LIMIT " . $start . "," . $pagesize;

                }

                $sql = "SELECT * FROM {$this->_prefix['primary']}goods_data WHERE " . $where . " ORDER BY " . $orderby . $limit;

                $rs = $this->sql($sql);

                if ($rs) {
                    foreach ($rs as $r) {

                        if ($r['thumb_docid'] > 0) {
                            $docids[] = $r['thumb_docid'];
                        } elseif ($r['pic_docid'] > 0) {
                            $docids[] = $r['pic_docid'];
                        }

                        $goods_ids[] = $r['goods_id'];

                    }

                    // 获取库存
                    $sql = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` IN (" . implode(",", $goods_ids) . ")";
                    $tmp = $this->sql($sql);

                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $goods_number[$r['goods_id']] = $r['number'];
                        }

                    }

                    if ($docids) {
                        $docs = $this->getDocs($docids);
                    }

                    foreach ($rs as $k => $r) {

                        if ($r['thumb_docid'] > 0 && $docs[$r['thumb_docid']]) {

                            $rs[$k]['thumb_docid'] = $docs[$r['thumb_docid']];

                        } elseif ($r['pic_docid'] > 0 && $docs[$r['pic_docid']]) {

                            $rs[$k]['thumb_docid'] = $docs[$r['pic_docid']];

                        }

                        if ($goods_number[$r['goods_id']] > 0) {
                            $rs[$k]['goods_number'] = $goods_number[$r['goods_id']];
                        } else {
                            $rs[$k]['goods_number'] = 0;
                        }

                    }

                }

            }

            // 获取分类
            if ($para['caid'] > 0) {
                $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE `caid`=" . $para['caid'];
                $caid = $this->db->getrow($sql);
            }

            // 获取品牌
            if ($para['brand_id'] > 0) {
                $sql   = "SELECT * FROM {$this->_prefix['primary']}brand WHERE `brand_id`=" . $para['brand_id'];
                $brand = $this->db->getrow($sql);
                if ($brand['brand_pic'] > 0) {
                    $tmp = $this->getDocs($brand['brand_pic']);

                    if ($tmp[$brand['brand_pic']]) {
                        $brand['logo'] = $tmp[$brand['brand_pic']];
                    }
                }
            }
        }

        return array(
            'page'        => $page,
            'maxpage'     => ceil($cnt / $pagesize),
            'count'       => $cnt,
            'data'        => $rs,
            'para'        => $para,
            'docs'        => $docs,
            'brand'       => $brand,
            'cateAdvlist' => $cateAdvlist,
            'caid'        => $caid['name'],
        );

    }
    public function getRelevances($relevance_id)
    {

        if ($relevance_id > 0) {

            $sql   = "SELECT `goods_ids`,`option_name` FROM {$this->_prefix['primary']}goods_relevance WHERE `status`=1 AND `id`=" . $relevance_id;
            $reles = $this->db->getrow($sql);
            if ($reles['goods_ids'] != "") {
                $tmp = explode(",", $reles['goods_ids']);
                if (is_array($tmp)) {
                    foreach ($tmp as $r) {
                        if ($r != "") {
                            $newids[] = $r;
                        }

                    }
                }

                if ($newids) {
                    $sql            = "SELECT `goods_id`,`rele_title`,`goods_name` FROM {$this->_prefix['primary']}goods_data WHERE `is_on_sale`=1 AND `is_delete`=0 AND `goods_id` IN (" . implode(",", array_unique($newids)) . ")";
                    $reles['goods'] = $this->sql($sql);

                    return $reles;
                }

            }

        }

    }

    //商品图片
    public function getPic($docid, $type = false)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            if (!$type) {
                $where = " WHERE `docid`=" . intval($docid);
            } else {

                $where = " WHERE `docid` IN (" . $docid . ")";
            }

        }

        $sql = "SELECT `docid`,`filename`,`create_time`,imgwh FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $k => $r) {
                $doc[$k]['img_url'] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];
                $doc[$k]['imgwh']   = $r['imgwh'];
            }
            return $doc;
        }

    }

    //分类
    public function cate($caid = 0, $isfucaid = false, $shopid = 0)
    {
        if ($isfucaid) {
            $tsql = " AND `fucaid`=" . intval($caid);
        } elseif ($caid > 0) {
            $tsql = " AND `caid`=" . intval($caid);
        }

        if ($shopid > 0) {
            $tsql = " AND `shopid`=" . intval($shopid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1  " . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC ";

        if ($caid > 0 && !$isfucaid) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                if ($isfucaid) {
                    $newdata = $data;
                } else {
                    foreach ($data as $r) {
                        if ($r['fucaid'] == 0) {
                            if ($r['docid']) {
                                $docid      = $r['docid'];
                                $img        = $this->getDocs($docid);
                                $r['docid'] = $img[$docid];
                            } else {
                                $r['docid'] = "/style/images/fenlei/default_cate.png";
                            }

                            $newdata[$r['fucaid']][] = $r;

                        } else {
                            $newdata[$r['fucaid']][$r['caid']] = $r;
                            if ($newdata[$r['fucaid']][$r['caid']]['docid'] > 0) {
                                $docid                                      = $r['docid'];
                                $img                                        = $this->getDocs($docid);
                                $newdata[$r['fucaid']][$r['caid']]['docid'] = $img[$docid];
                            } else {
                                $newdata[$r['fucaid']][$r['caid']]['docid'] = "/style/images/fenlei/default_cate.png";
                            }
                        }

                    }
                }
            }
        }
        return $newdata;
    }

    //品牌分类
    public function brand()
    {
        // 获取所有国家
        $sql     = "SELECT * FROM {$this->_prefix['primary']}brand_category WHERE `stat`=1  ORDER BY `stat` ASC ,`sort` ASC ";
        $country = $this->sql($sql);
        if ($country) {
            foreach ($country as $r) {
                if ($r['docid'] > 0) {
                    $docids[] = $r['docid'];
                }
            }
        }

        // 获取所有品牌
        $sql    = "SELECT * FROM {$this->_prefix['primary']}brand WHERE `stat`=1 ORDER BY `weight` DESC";
        $brands = $this->sql($sql);

        if ($brands) {
            foreach ($brands as $r) {
                $caid[$r['caid']][$r['brand_id']] = $r;

                if ($r['brand_pic'] > 0) {
                    $docids[] = $r['brand_pic'];
                }
            }

        }

        if ($docids) {
            $docs = $this->getDocs($docids);
        }

        //print_r($brand);
        foreach ($country as $key => $r) {

            if ($r['docid'] > 0 && $docs[$r['docid']]) {
                $country[$key]['docid'] = $docs[$r['docid']];
            } else {
                $country[$key]['docid'] = "/style/images/fenlei/default_country.png";
            }

            if ($caid[$r['caid']]) {
                $country[$key]['goods'] = $caid[$r['caid']];

                //品牌图标
                foreach ($country[$key]['goods'] as $k => $v) {

                    if ($v['brand_pic'] > 0 && $docs[$v['brand_pic']]) {

                        $country[$key]['goods'][$k]['cover_pic'] = $docs[$v['brand_pic']];
                    } else {
                        $country[$key]['goods'][$k]['cover_pic'] = "/style/images/fenlei/default_brand.png";
                    }
                }
            }

        }
        return $country;

    }

    // 获取购物车商品数量
    public function getCartNum()
    {

        if ($this->_user['uid'] > 0) {
            $sql     = "SELECT SUM(cr.`number`) AS `cnt` FROM {$this->_prefix['primary']}goods_cart cr INNER JOIN {$this->_prefix['primary']}goods_data gd ON cr.`uid`=" . $this->_user['uid'] . " AND gd.`goods_id` = cr.`goods_id` AND gd.`is_on_sale`=1 AND gd.`is_delete`=0";
            $cartnum = $this->db->getone($sql);
            if ($cartnum > 99) {
                $cartnum = 99;
            }
        }

        if (!$cartnum) {
            $cartnum = 0;
        }

        return $cartnum;
    }

    // 执行商品收藏
    public function collectionGoods($goods_id)
    {
        $code = 900;
        $user = $this->checkAuth(false);
        if ($user['uid'] > 0) {
            $goods_id = intval($goods_id);
            if ($goods_id > 0) {
                $sql           = "SELECT `id` FROM {$this->_prefix['primary']}goods_collection WHERE `uid`=" . $user['uid'] . " AND `goods_id`=" . $goods_id . " AND `state`=1";
                $collection_id = $this->db->getone($sql);
                // 删除
                if ($collection_id > 0) {
                    $sql = "DELETE FROM {$this->_prefix['primary']}goods_collection WHERE `id`=" . $collection_id;
                    $rcs = $this->sql($sql);
                    if ($rcs > 0) {
                        $code   = 200;
                        $result = 0;
                    } else {
                        $code = 403;
                    }
                } else {
                    $sql = "INSERT INTO {$this->_prefix['primary']}goods_collection (`uid`,`goods_id`,`state`,`create_time`) VALUES (" . $user['uid'] . "," . $goods_id . ",1," . $_SERVER['REQUEST_TIME'] . ")";
                    $rcs = $this->sql($sql);
                    if ($rcs > 0) {
                        $code   = 200;
                        $result = 1;

                        $this->saveGoodsLog($goods_id, 2);

                    } else {
                        $code = 403;
                    }
                }
            }

        }

        return array(
            'code'   => $code,
            'result' => $result,
        );
    }

    // 保存商品收藏浏览记录
    public function saveGoodsLog($goods_id, $type = 1)
    {
        $uid = $this->_user['uid'] > 0 ? $this->_user['uid'] : 0;
        if ($goods_id > 0) {
            $sql = "INSERT INTO {$this->_prefix['primary']}goods_log (`goods_id`,`uid`,`type`,`create_time`) VALUES (" . $goods_id . "," . $uid . "," . $type . "," . $_SERVER['REQUEST_TIME'] . ")";
            $this->sql($sql);
        }
    }

    // SCWS
    public function getScwsWord($str)
    {
        $scws = scws_new();
        $scws->set_charset('utf8');
        $scws->set_duality(true); //散字自动二元
        $scws->set_ignore(true); //清除标点符号
        $scws->set_multi(3); //最短词，二元
        $scws->send_text(strtolower($str));
        while ($res = $scws->get_result()) {
            foreach ($res as $tmp) {
                $word[] = str_replace("'", "", $tmp['word']);
            }
        }
        $word = array_unique($word);

        $scws->close();
        return $word;
    }

    // 获取关键词相关商品ID
    public function getScwsData($words = array())
    {
        if (count($words) > 0) {
            foreach ($words as $word) {
                $sql = "SELECT `word_id` FROM {$this->_prefix['primary']}scws_word WHERE `word`='" . $word . "' LIMIT 1";
                $tmp = $this->db->getone($sql);
                if ($tmp > 0) {
                    $word_ids[] = $tmp;
                }
            }

            if ($word_ids) {

                $len = count($word_ids);

                if ($len > 2) {
                    $len = 2;
                }

                $sql = "SELECT `goods_id` FROM (SELECT COUNT(`word_id`) AS `cnt`,`goods_id`  FROM {$this->_prefix['primary']}scws_data WHERE `word_id` IN (" . implode(",", $word_ids) . ") GROUP BY `goods_id` ) AS tmp_table WHERE `cnt`>=" . $len . " ORDER BY `cnt` DESC,`goods_id` DESC LIMIT 100";
                $tmp = $this->sql($sql);
                if ($tmp) {

                    foreach ($tmp as $r) {
                        $goods_ids[] = $r['goods_id'];
                    }

                    // 统计有效在售商品
                    $sql = "SELECT `goods_id` FROM {$this->_prefix['primary']}goods_data WHERE `goods_id` IN (" . implode(",", $goods_ids) . ") AND `is_on_sale`=1 AND `is_delete`=0";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $mid[$r['goods_id']] = $r['goods_id'];
                        }

                        foreach ($goods_ids as $r) {
                            if ($mid[$r]) {
                                $new_goods_ids[] = $r;
                            }
                        }

                        if ($new_goods_ids) {

                            return array(
                                'goods_ids' => array_unique($new_goods_ids),
                                'sql'       => $sql,
                            );
                        }

                    }
                }
            }
        }

    }

    public function getNewOrderDetail()
    {
        $userDetail = array();
        $start_time = time() - (60 * 12);
        $end_time   = time();
        $where      = "`pay_status`> 0   AND `order_status` = 1";

        $sql  = "SELECT `uid` FROM {$this->_prefix['primary']}order_info WHERE " . $where . " AND `add_time` >=" . $start_time . " AND `add_time` <=" . $end_time;
        $data = $this->db->getrow($sql);
        if (empty($data['uid'])) {
            //粒田用户资料$user_array  二维数组
            $user_array = $this->getMemberOldList();
            $temp       = array_rand($user_array, 1); //随机取1个
            $userDetail = $user_array[$temp];

        } else {
            $sql        = "SELECT `uid`,`realname`,`name`,`wechat_headimgurl`,`headimgurl` FROM {$this->_prefix['primary']}member_account WHERE  `uid`=" . $data['uid'];
            $userDetail = $this->db->getrow($sql);
            if ($userDetail['headimgurl'] > 0) {

                $pic                      = $this->getPic($userDetail['headimgurl']);
                $userDetail['headimgurl'] = $pic[0]['img_url'];
            } else {

                $userDetail['headimgurl'] = $userDetail['wechat_headimgurl'];
            }

        }

        if (empty($userDetail)) {
            $userDetail = array();

        }

        return array('data' => $userDetail);
    }
    //获取最新订单显示的假用户信息
    public function getMemberOldList()
    {
        $sql      = "SELECT * FROM {$this->_prefix['primary']}weixin_rand";
        $userList = $this->sql($sql);
        return $userList;

    }

    // 获取用户信息
    public function getRecode($uid = 0)
    {
        if ($uid < 1) {
            $uid = $this->_user['uid'];
        }

        $sql = "SELECT `recode` FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $uid;
        return $this->db->getrow($sql);

    }

    // 获取用户等级
    public function getMemberLevel()
    {
        return $this->db->getone("SELECT `member_level` FROM {$this->_prefix['primary']}member_account WHERE `uid`=".$this->_user['uid']);
    }

}
